package com.xingkeduo.util;

import com.alibaba.fastjson.JSON;
import com.gexin.rp.sdk.base.IPushResult;
import com.xingkeduo.AppPush;
import com.xingkeduo.dto.WebsocketMessageResponse;
import com.xingkeduo.pojo.service.ScreenService;
import com.xingkeduo.pojo.table.Screen;
import com.xingkeduo.util.pojo.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chi  2019-05-24 17:26
 **/
@Slf4j
@Component
public class ScreenMapUtil {

    @Resource
    private ScreenService screenService;

    /**
     * 登陆websocket    key=设备号
     */
    public static final Map<String, Session> LOGIN_SESSION_MAP = new ConcurrentHashMap<>();

    /**
     * 数据传输websocket    key=设备号
     */
    public static final Map<String, Session> TRANS_SESSION_MAP = new ConcurrentHashMap<>();

    /**
     * 设备号  key=门店id,   value  = 设备号 列表
     */
    public static final Map<String, Set<String>> STORE_LIST_MAP = new ConcurrentHashMap<>();


    public  synchronized void putStore(String identificationCode, String storeId, Session session) {
        Set<String> strings = Optional.ofNullable(STORE_LIST_MAP.get(storeId)).orElseGet(ConcurrentHashMap::newKeySet);
        strings.add(identificationCode);
        STORE_LIST_MAP.put(storeId, strings);

        TRANS_SESSION_MAP.put(identificationCode, session);
    }

    public  synchronized void removeStore(String identificationCode, String storeId) {
        Set<String> strings = STORE_LIST_MAP.get(storeId);
        if (strings != null) {
            strings.remove(identificationCode);
        }

        TRANS_SESSION_MAP.remove(identificationCode);
    }


    /**
     * 数据传输发送消息
     * @param storeId
     * @param message
     */
    public  void transferSendMessage(String storeId, WebsocketMessageResponse message) {
        log.info("transferSendMessage:  storeId:{}, message:{}", storeId, JSON.toJSONString(message));


        /*Set<String> strings = STORE_LIST_MAP.get(storeId);
        if (strings == null) {
            //log.info("{}数据传输发送消息 无设备号",storeId);
        }else {
            strings.forEach(s -> {
                try {
                    Session session = TRANS_SESSION_MAP.get(s);
                    if(session!=null){
                        synchronized (session){
                            session.getBasicRemote().sendText(JSON.toJSONString(message));
                            log.error("{}的{} transferSendMessage发送成功", storeId, s);
                        }
                    }
                } catch (Exception e) {
                    log.error("{}的{} transferSendMessage发送失败:{}", storeId, s, e);
                }
            });
        }*/

        if (WebsocketMessageResponse.MessageTypeEnum.WORKPAD.equals(message.getMessageTypeEnum())) {
            message.setData(null);
        }

        Optional<List<Screen>> byStoreId = screenService.getByStoreId(storeId);
        if(byStoreId.isPresent()){
            List<Screen> screens = byStoreId.get();

            for (Screen screen : screens) {
                AppPush.pushMessage(screen.getClientId(), message);
            }
        }

    }

    /**
     * 登陆发送消息
     *
     * @param identificationCode
     * @throws Exception
     */
    public  void loginSendMessage(String identificationCode, WebsocketMessageResponse message) throws Exception{
        log.info("loginSendMessage:  identificationCode:{}, message:{}", identificationCode, JSON.toJSONString(message));

        IPushResult iPushResult = AppPush.pushMessage(identificationCode, message);

        if(iPushResult==null){
            throw new BusinessException(BusinessException.Type.DEFAULT,"请重启下单屏后再扫码");
        }
        Map<String, Object> response = iPushResult.getResponse();

        if(!"successed_online".equals(response.get("status").toString())){
            throw  new BusinessException(BusinessException.Type.DEFAULT,"请重启下单屏后再扫码");
        }

        /*Session session = LOGIN_SESSION_MAP.get(identificationCode);
        if(session!=null){
            session.getBasicRemote().sendText(JSON.toJSONString(message));
        }*/

    }
}
